<template>
  <div>
    <div class="search-filter-container no-select">
      <div class="search-filter-area">
        <h3>{{ lineName }}</h3>
      </div>
    </div>
    <div id="sec-container" class="content"></div>


    <el-dialog
        top="3vh"
        draggable
        v-model="dialogRiskDetailVisible"
        :close-on-click-modal="true"
    >
      <RiskSectionDetial  v-if="showData" :show-data="showData"></RiskSectionDetial>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {Graph} from '@antv/g6';
import {useGridStore} from "../store/gridData";
import {useRoute} from "vue-router";
import req from "../tools/request";
import RiskSectionDetial from "./RiskSectionDetial.vue";

const dialogRiskDetailVisible = ref(false)
const showData = ref(null)
const lineName = ref(null)
const zoom = ref(1.0)

let graph = null

function clickNode(evt) {
  showData.value = null
  const {targetType, target} = evt;
  if (targetType === 'node') {
    console.log('点击了节点:', target.id);
  } else if (targetType === 'edge') {
    console.log('点击了边:', target.id);

    console.log(target.id);
    console.log(useGridStore().state)
    const foundItem = useGridStore().state.cableSegmentData.find(item => `${item.cable_section_number}` === target.id);
    if (foundItem) {
      console.log('找到的项:', foundItem);
      showData.value = foundItem
    } else {
      console.log('未找到符合条件的项');
    }
    dialogRiskDetailVisible.value = true;
  } else {
    console.log('点击了画布空白处');
  }
}

function transformData(data) {
  const nodes = [];
  const edges = [];

  data.forEach(item => {
    // 添加节点
    if (!nodes.some(node => node.id === item.start)) {
      nodes.push({
        id: `${item.start}`, label: `${item.start}`
      });
    }
    if (!nodes.some(node => node.id === item.end)) {
      nodes.push({
        id: `${item.end}`, label: `${item.end}`
      });
    }

    // 添加边
    edges.push({
      id: item.cable_section_number + "",
      source: `${item.start}`,
      target: `${item.end}`,
      label: `${item.line_name}`,
      risk_level: `${item.risk_level}`,
    });
  });

  console.log({nodes, edges})
  return {nodes, edges};
}

onMounted(() => {
  const route = useRoute(); // 获取当前路由对象
  lineName.value = route.query.line_name;
  console.log(lineName.value)
  console.log(route.query.line_name)
  req.get('/cable_segment_grid_data').then(res => {
    useGridStore().setCableSegmentGridData(res.data.data)
    req.get('/data').then(res => {
      useGridStore().setData(res.data)
      req.get('/cable_segment_data').then(res => {
        useGridStore().setCableSegmentData(res.data.data.cable_section_data)
        showData.value = useGridStore().state.data[route.query.line_name]
        console.log(showData.value)
        let data = transformData(showData.value)

        let element = document.getElementById('sec-container')
        graph = new Graph({
          container: element,
          width: element.clientWidth,
          height: element.clientHeight,
          animation: false,
          layout: {
            type: 'd3-force',
            link: {
              distance: 50,
              strength: 2
            },
            collide: {
              radius: 100,
            },
          },
          behaviors: ['drag-element', 'drag-canvas', 'zoom-canvas', 'hover-activate', {
            type: 'click-select',
            degree: 1,
            state: 'active',
            unselectedState: 'inactive',
            multiple: true,
            trigger: ['shift'],
            onClick: clickNode
          }, {
            key: 'auto-adapt-label',
            type: 'auto-adapt-label',
            padding: 0,
            throttle: 200
          }],
          node: {
            style: {
              label: true,
              labelFill: '#000000',
              labelText: (d) => d.id,
              labelFontSize: 12, // 标签字体大小
              labelFontWeight: 'normal', // 标签字体粗细
              labelPlacement: 'bottom', // 标签相对于节点主图形的位置
            },
          },
          edge: {
            style: {
              stroke: (d) => {
                if (d.risk_level === '高风险') return 'rgba(255,0,0,0.75)';
                if (d.risk_level === '中风险') return 'rgba(255,212,0,0.75)';
                if (d.risk_level === '低风险') return 'rgba(15,255,0,0.82)';
                return '#000'
              },
              // stroke: '#f10000',
              lineWidth: 6, // 边的宽度
              label: true, // 开启边标签展示
              labelText: (d) => d.id, // 边标签文字
              labelPlacement: 'center', // 边标签相对于边的位置
              labelFill: '#000000', // 边标签文字颜色
              labelOffsetY: 15, // 边标签在y轴方向上的偏移量
            },
          },
          data,
          plugins: [
            {
              type: 'toolbar',
              getItems: () => [
                {id: 'zoom-in', value: 'zoom-in'},
                {id: 'zoom-out', value: 'zoom-out'},
                {id: 'auto-fit', value: 'auto-fit'},
              ],
              onClick: (value) => {
                // 处理按钮点击事件
                if (value === 'zoom-in') {
                  zoom.value += 0.1
                  zoom.value = Math.min(zoom.value, 3)
                  graph.zoomTo(zoom.value);
                } else if (value === 'zoom-out') {
                  zoom.value -= 0.1
                  zoom.value = Math.max(zoom.value, 0.1)
                  graph.zoomTo(zoom.value);
                } else if (value === 'auto-fit') {
                  graph.fitView();
                }
              },
            },
          ],
        });
        graph.render()
      })
    })
  })

});
</script>

<style scoped>
.search-filter-container {
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  user-select: none;
}

.search-filter-area {
  display: flex;
  align-items: center;
  gap: 10px;
}

#sec-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 700px;
  width: 100%;
  min-width: 1000px;
  overflow: hidden;
}
</style>
